//
//  MyJobDetailViewController.swift
//  ezyform
//
//  Created by MoennigQ on 10/12/18.
//  Copyright © 2018 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SnapKit
import MBProgressHUD
import HandyJSON
import SwiftyJSON
import CoreLocation
import MJRefresh
import RxCocoa
import RxSwift
import RxGesture
class ServiceJobDetailViewController: BidBaseViewController {
    lazy var disposeBag = DisposeBag()
    var reloadServiceJobsListClosure: (()->Void)?//关闭detail后，要刷新installation list中对应的cell，处理cell中某些数据的改变（状态，数量，姓名等）
    var customView = ServiceDetailView()
    //only one record
    var myOffers = [ServiceDetailOfferModel]()
    //
    //history list
    var historyList = [ServiceDetailHistoryModel]()
    var firstLoading: Bool = true
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initUI()
        
        self.loadData(true)
    }
    func initUI(){
        self.view = self.customView
        self.customView.setTitle("Loading...")
        //Retry
        self.customView.loadFaildView.retryBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.loadData(true)
        }).disposed(by: self.disposeBag)
        self.customView.backToPreBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.backToPre()
        }).disposed(by: self.disposeBag)
        self.customView.refreshBtn.rx.tap.subscribe(onNext: { [weak self] _ in
            self?.loadData(true)
        }).disposed(by: self.disposeBag)
        //Preview images
        self.customView.tabDetailView.jobDetailSectionView.previewImagesClosure = {[weak self] (row) in
            self?.previewImages(row)
        }
        //Call owner phone
        self.customView.tabDetailView.jobDetailSectionView.callPhoneBtn.rx.tap.subscribe(onNext: { _ in
            InstallationDetailVCHelper.shared.callPhone(ServiceDetailModelHelper.shared.serviceDetailModel.owner_address.phone)
        }).disposed(by: self.disposeBag)
        //send sms to owner
        self.customView.tabDetailView.jobDetailSectionView.sendMsgBtn.rx.tap.subscribe(onNext: { _ in
            ServiceDetailVCHelper.shared.sendSMS(ServiceDetailModelHelper.shared.serviceDetailModel.owner_address.phone)
        }).disposed(by: self.disposeBag)
        //Call publisher phone
        self.customView.tabDetailView.publisherDetailSectionView.callPhoneBtn.rx.tap.subscribe(onNext: { _ in
            InstallationDetailVCHelper.shared.callPhone(ServiceDetailModelHelper.shared.serviceDetailModel.publisher_phone)
        }).disposed(by: self.disposeBag)
        //set off job
        self.customView.starJobClosure = {[weak self] in
            Tool().showAlertViewWithTwoBtns(message: "Are you sure to start service job?",noClosure: nil) {
                self?.startJob()
            }
        }
        //finish job
        self.customView.finishJobClosure = {[weak self] in
            Tool().showAlertViewWithTwoBtns(title:"Are you sure you have completed the service job? ",message: "Checklist cannot be edited after the job is finished.",noClosure: nil) {
                self?.toFinishJob()
            }
        }
        //loading history list
        self.customView.clickTabHistoryClosure = {[weak self] in
            self?.loadHistoryList()
        }
        //操作checklist image
        self.customView.tabChecklistView.tableView.toImageListClosure = {[weak self] (row) in
            guard let strongSelf = self else {return}
            strongSelf.toImageListVC(row)
        }
        //操作checklist text
        self.customView.tabChecklistView.tableView.toEditTextClosure = {[weak self] (checklistModel) in
            guard let strongSelf = self else {return}
            strongSelf.showEditCheckListText(checklistModel)
            
        }
        //操作checklist bool
        self.customView.tabChecklistView.tableView.toClickChecklitBoolItemClosure = {[weak self] (row) in
            guard let strongSelf = self else {return}
            strongSelf.toClickBoolItemOfChecklist(row)
        }
        //MARK: - support function - Flush upload
        self.customView.tabChecklistView.supportFunctionView.rx.tapGesture().when(.recognized).subscribe(onNext: { [weak self] _ in
            guard let strongSelf = self else { return  }
            guard  ServiceDetailModelHelper.shared.serviceDetailModel.canEditJobDetailFlag else {return}
            strongSelf.flushUpload(.flushUpload)
        }).disposed(by: self.disposeBag)
    }
    private func loadData(_ loadingFlag: Bool){
        let vc = ServcieDetailService()
        vc.setBlockAfterNetwork({ (obj , _) in
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            self.customView.setTitle(ServiceDetailModelHelper.shared.serviceDetailModel.number)
            self.customView.tabDetailView.setData(ServiceDetailModelHelper.shared.serviceDetailModel)
            self.customView.setBottomBtnsByStatus(ServiceDetailModelHelper.shared.serviceDetailModel)
            
            self.loadHistoryList()
            self.customView.showDetailView()
            if self.firstLoading {
                self.firstLoading = false
                //默认选中detail btn
                self.customView.changeTab(self.customView.topBarView.detailBtn)
            }
        }) { (code,err) in
            if loadingFlag {
                ModelViewUtil.shared.hideLoadingView()
            }
            if code == APICustomStatusCode.RequestFaild.rawValue{//网络请求错误才显示Retry
                self.customView.showFaildView()
            }
            Tool().showErrorInfo(code,err)
        }
        if loadingFlag {
            ModelViewUtil.shared.showLoadingView(R.string.localizable.loading())
        }
        vc.getMyBidJobDetail(ServiceDetailModelHelper.shared.serviceDetailModel.serviceID,cacheFlag: true)
    }
    //MARK: - Start Job
    private func startJob(){
        if !Connectivity.isConnectedToInternet {
            Tool().showFailureInfo()
            return
        }
        LocationManager.shared.subscription(.single).fetchWithCompletion {[weak self](location, error) in
            guard let strongSelf = self else {
                return
            }
            
            if location != nil {
                CLGeocoder().reverseGeocodeLocation(location!, completionHandler: {(placemarks, error)->Void in
                    //Geocoding requests are rate-limited for each app, so making too many requests in a short period of time may cause some of the requests to fail.
                    var combine = ""
                    if  placemarks != nil && placemarks!.count > 0{
                        let pm = placemarks![0]
                        if pm.location != nil {
                            let latitude = String(format: "%.2f", pm.location!.coordinate.latitude)
                            let longitude = String(format: "%.2f", pm.location!.coordinate.longitude)
                            
                            combine = latitude.appending(",") + longitude
                        }
                    }
                    strongSelf.requestStartJob(combine)
                })
            }else{
                strongSelf.requestStartJob()
            }
        }
        
        
    }
    private func requestStartJob(_ locationStr: String = ""){
        if Connectivity.isConnectedToInternet {
            
            let vm = ServcieDetailService()
            vm.setBlockAfterNetwork({ (result , _) in
                ModelViewUtil.shared.hideLoadingView()
                self.loadData(false)
                
            }) { (code,err) in
                ModelViewUtil.shared.hideLoadingView()
                self.loadData(false)
                Tool().showErrorInfo(code, err)
            }
            //add Loading view
            ModelViewUtil.shared.showLoadingView(NSLocalizedString("pvd.detail.startJob", comment: ""))
            vm.startJob(locationStr)
        }else{
            Tool().showFailureInfo()
        }
    }
    @objc func reloadData(){
        self.loadData(true)
    }
    private func loadHistoryList(){
        let vc = ServcieDetailService()
        vc.setBlockAfterNetwork({ (obj , _) in
            let json = JSON(obj!)
            
            if let list = (JSONDeserializer<ServiceDetailHistoryModel>.deserializeModelArrayFrom(json: json.rawString()) as? Array<ServiceDetailHistoryModel>){
                ServiceDetailModelHelper.shared.serviceDetailModel.historyList = list
                ServiceDetailModelHelper.shared.historyList.onNext(ServiceDetailModelHelper.shared.serviceDetailModel.historyList)
                self.customView.tabHistoryView.tableView.showResultView(nodataFlag: list.count == 0 ? true: false)
            }
            
        }) { (_,_) in
        }
        
        vc.getHistoryList(ServiceDetailModelHelper.shared.serviceDetailModel.serviceID)
    }
    //MARK: - finish job
    private func toFinishJob(){
        if !Connectivity.isConnectedToInternet {
            Tool().showFailureInfo()
            return
        }
        if ServiceDetailModelHelper.shared.serviceDetailModel.isInstallerFlag {//installer才能finish job
            //local data need to upload before finish job
            if ServiceDetailModelHelper.shared.serviceDetailModel.detailModifyFlag {
                //finish job的时候如果有本地数据，弹出框中增加upload的button
                Tool().showAlertViewWithTwoBtns(message: NSLocalizedString("pvd.detail.localdata.check.uploaded", comment: ""), cancelStr: "Cancel", confirmStr: "Upload&Continue", yesClosure:  {
                    self.flushUpload(.finishJob)
                })
            }else{
                self.finishJob()
            }
        }
    }
    //MARK: - finish job API
    private func finishJob(){
        if Connectivity.isConnectedToInternet {
            //校验checklit 所有的必填项
            if ServiceDetailVCHelper.shared.checkRequiredWhenFinishJob() {
                let vm = ServcieDetailService()
                vm.setBlockAfterNetwork({ (result , _) in
                    ModelViewUtil.shared.hideLoadingView()
                    self.loadData(false)
                    Tool().showAlertViewWithOneBtn(message: NSLocalizedString("pvd.detail.finishedJob", comment: ""))
                }) { (code,err) in
                    ModelViewUtil.shared.hideLoadingView()
                    self.loadData(false)
                    Tool().showErrorInfo(code, err)
                    
                }
                //add Loading view
                ModelViewUtil.shared.showLoadingView(NSLocalizedString("pvd.detail.finishJob", comment: ""))
                vm.finishJob()
            }
        }else{
            Tool().showFailureInfo()
        }

    }
    //MARK: - 预览图片
    private func previewImages(_ row: Int){
        let vc = BrowseImageViewController()
        let list: [BrowseImageData] = ServiceDetailModelHelper.shared.serviceDetailModel.images.map { BrowseImageData(image:$0.image) }
        vc.imagesArray = list
        vc.currentIndex = row
        self.navigationController?.pushViewController(vc,animated: true)
    }
    //MARK: - image
    private func toImageListVC(_ index: Int){
        guard index < ServiceDetailModelHelper.shared.serviceDetailModel.checklists.count else {
            return
        }
        let vc =  ServiceImagesListViewController()
        ServiceDetailModelHelper.shared.checklistModel = ServiceDetailModelHelper.shared.serviceDetailModel.checklists[index]
        self.navigationController?.pushViewController(vc,animated: false)
    }
    //MARK: - edit text
    fileprivate func showEditCheckListText(_ serverModel: PVDChecklistModel){
        let vc = EditChecklistTextViewController()
        serverModel.pvdId  = ServiceDetailModelHelper.shared.serviceDetailModel.serviceID
        serverModel.jobType = .serviceJob
        vc.serverModel = serverModel
        vc.saveClosure = {(checkModel) in
            //0.必须先插入数据库，因为broadCast时，有地方（flush upload）会用到本地数据的统计
            DBManager.shared.insertServiceChecklistData(model: checkModel)
            checkModel.oper_type = DataOperType.Add.rawValue
            //1.增加到当前list中，刷新数据
            if let index = ServiceDetailModelHelper.shared.serviceDetailModel.checklists.firstIndex(where: {$0.id == checkModel.id}){
                ServiceDetailModelHelper.shared.serviceDetailModel.checklists[index] = checkModel
                ServiceDetailModelHelper.shared.serviceDetailModel.broadCastChecklistData()
            }
            //2.上传
            UploadManager.shared.uploadServiceChecklistBoolOrText(checklistModel: checkModel)
        }
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //MARK: - image
    private func toClickBoolItemOfChecklist(_ index: Int){
        guard  ServiceDetailModelHelper.shared.serviceDetailModel.canEditJobDetailFlag else {return}
        let currentCheckListModel = ServiceDetailModelHelper.shared.serviceDetailModel.checklists[index]
        currentCheckListModel.pvdId  = ServiceDetailModelHelper.shared.serviceDetailModel.serviceID
        //1.local data exist
        if currentCheckListModel.answer == "true" {
            currentCheckListModel.answered_at = ""
            currentCheckListModel.answer = ""
            currentCheckListModel.full_name = ""
        }else{
            currentCheckListModel.answered_at = DateUtil().getCurrentDatetime()
            currentCheckListModel.answer = "true"
            currentCheckListModel.full_name = APPConfig.loginInfo.fullName
        }
        //0.必须先插入数据库，因为broadCastChecklistData时，有地方会用到本地数据
        DBManager.shared.insertServiceChecklistData(model: currentCheckListModel)
        currentCheckListModel.oper_type = DataOperType.Add.rawValue
        //1.增加到当前list中，刷新数据
        ServiceDetailModelHelper.shared.serviceDetailModel.checklists[index] = currentCheckListModel
        ServiceDetailModelHelper.shared.serviceDetailModel.broadCastChecklistData()
        //3.上传
        UploadManager.shared.uploadServiceChecklistBoolOrText(checklistModel: currentCheckListModel)
    }
    //MARK: - 上传job的 本地数据，且显示uploading 信息
    private func flushUpload(_ toContinueType: FlushUploadType){
        if Connectivity.isConnectedToInternet  {
            if ServiceDetailModelHelper.shared.serviceDetailModel.detailModifyFlag{
                let view = FlushUploadView()
                self.navigationController?.view.addSubview(view)
                view.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
                //停止Flush reupload
                view.stopFlushUploadClosure = { [weak self] in
                    guard let strongSelf = self else { return  }
                    UploadManager.shared.cancelFlushUpload()
                    strongSelf.loadData(false)
                    view.removeFromSuperview()
                }
                UploadManager.shared.uploadLocalDataByServiceJob(ServiceDetailModelHelper.shared.serviceDetailModel.serviceID, uploadingClosure: { [weak self] (needUploadCnt,uploadSuccessCnt, uploadFaildCnt) in
                    guard let strongSelf = self else { return  }
                    view.uploadingLabel.text = "Uploading \(uploadSuccessCnt)/\(needUploadCnt)"
                    if needUploadCnt == uploadSuccessCnt + uploadFaildCnt {//上传完毕
                        strongSelf.loadData(false)
                        if let _ = view.superview {//可能stopFlushUpload时候被remove掉了，所以此处要判断下
                            view.removeFromSuperview()
                        }
                        if needUploadCnt == uploadSuccessCnt {//上传成功
                            if toContinueType == .flushUpload {//单纯的上传
                                //无处理
                            }else{//finish job
                                ServiceDetailVCHelper.shared.cacheData { _ in
                                    strongSelf.finishJob()
                                }
                            }
                        }else{//上传失败
                            Tool().showAlertViewWithTwoBtns(title: "Partial upload failed", message: "Some data failed to upload, please upload again.",cancelStr: "Cancel", confirmStr: "Re-upload",noClosure: nil, yesClosure: {
                                strongSelf.flushUpload(.flushUpload)
                            })
                        }
                    }
                })
            }
        }else{
            Tool().showFailureInfo()
        }
    }
    override func backToPre() {
        self.reloadServiceJobsListClosure?()
        self.navigationController?.popViewController(animated: true)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
}
